Popular Searches
Popular Course Categories
Popular Courses

Understanding HttpServletRequest and HttpServletResponse

Understanding HttpServletRequest and HttpServletResponse

HTTP Request and Response Handling

Understanding HttpServletRequest and HttpServletResponse in Java Servlets

Course: Advanced Java Training

Topic: Understanding HttpServletRequest and HttpServletResponse

Course Link: Advanced Java Training Course

Demo Link: Register for a Free Course Demo

Official Website: JustAcademy


1. Introduction to HttpServletRequest and HttpServletResponse

In Java Servlet programming, HttpServletRequest and HttpServletResponse are two essential interfaces used to handle communication between a client, such as a web browser, and a Java web application running on a servlet container.

When a user submits a form, clicks a link, or opens a webpage, the browser sends an HTTP request to the server. The servlet container receives this request and provides request and response objects to the servlet. The servlet processes the incoming information and generates an HTTP response that is sent back to the client.

  • HttpServletRequest: Provides access to information sent by the client, including parameters, headers, cookies, session data, and request details.
  • HttpServletResponse: Allows the servlet to create the response, including the response body, status code, headers, cookies, and redirects.

2. What Is HttpServletRequest?

HttpServletRequest is an interface from the jakarta.servlet.http package in modern Jakarta-based applications. In older Java EE applications, the equivalent package is javax.servlet.http.

It extends the general servlet request functionality and provides HTTP-specific methods that allow a servlet to read information about an incoming HTTP request.

Key Responsibilities

  • Retrieve form data and query parameters.
  • Read HTTP request headers.
  • Access cookies sent by the browser.
  • Retrieve session information.
  • Identify the HTTP method, request URI, and context path.
  • Read request body data when required.
  • Access request attributes set by filters or other server-side components.

3. What Is HttpServletResponse?

HttpServletResponse is an interface used by a servlet to construct and control the HTTP response sent to the client.

After processing the request, the servlet uses this object to return HTML, JSON, plain text, or other supported response content. It can also set the HTTP status code, configure headers, add cookies, and redirect the client to another URL.

Key Responsibilities

  • Set the HTTP response status code.
  • Specify the response content type and character encoding.
  • Write text or binary content to the response body.
  • Set HTTP response headers.
  • Add cookies to the response.
  • Redirect the browser to another resource.
  • Send error responses when necessary.

4. Difference Between HttpServletRequest and HttpServletResponse

Basis HttpServletRequest HttpServletResponse
Purpose Reads incoming request information. Creates outgoing response information.
Direction Client to server. Server to client.
Parameters Reads submitted parameters. Does not provide request-parameter retrieval.
Headers Reads request headers. Sets response headers.
Cookies Reads cookies sent by the client. Adds cookies to the response.
Session Provides access to the HTTP session. Can configure session-related cookies indirectly through application and container settings.
Output Provides access to request data and input streams. Provides writers and output streams for response content.
Common methods getParameter(), getHeader(), getMethod() setStatus(), setContentType(), sendRedirect()

5. Understanding the HTTP Request-Response Lifecycle

The following steps explain how these interfaces work together during a typical servlet request.

  1. The user opens a page or submits a form in a browser.
  2. The browser sends an HTTP request to the server.
  3. The servlet container receives the request and identifies the appropriate servlet.
  4. The container creates or provides the HttpServletRequest and HttpServletResponse objects.
  5. The servlet reads request parameters, headers, or other data.
  6. The servlet executes business logic or calls a service or database layer.
  7. The servlet sets the response status, content type, headers, and response body.
  8. The container sends the response to the browser, which displays or processes the returned content.

6. Creating a Basic Servlet

The following example demonstrates how a servlet receives an HTTP request and returns a response. This example uses the Jakarta Servlet API, which is common in modern Jakarta EE environments.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello from Java Servlet!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Explanation

  • @WebServlet("/hello") maps the servlet to the /hello URL within the web application's context.
  • doGet() handles HTTP GET requests.
  • HttpServletRequest request represents the incoming request.
  • HttpServletResponse response represents the outgoing response.
  • setContentType("text/html") indicates that the response contains HTML.
  • setCharacterEncoding("UTF-8") specifies the character encoding for the response writer.
  • getWriter() returns a PrintWriter used to write text to the response.

In an older Java EE project, replace the jakarta.servlet imports with their corresponding javax.servlet imports and use a compatible servlet container.

7. Retrieving Request Parameters

Request parameters are commonly submitted through HTML forms or included in a URL query string. The getParameter() method retrieves a parameter as a string.

HTML Form Example

<form action="welcome" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username">
    <button type="submit">Submit</button>
</form>

Servlet Example

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {

        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        if (username == null || username.isBlank()) {
            response.setStatus(
                HttpServletResponse.SC_BAD_REQUEST
            );
            response.getWriter().println(
                "Username is required."
            );
            return;
        }

        response.getWriter().println(
            "Welcome, " + username + "!"
        );
    }
}

Important: Set the request character encoding before reading form parameters when the application needs a specific encoding. Validate all incoming values before using them in business logic.

Common Parameter Methods

Method Description
getParameter(String name) Returns one parameter value as a string.
getParameterValues(String name) Returns all values for a parameter, such as multiple selected checkboxes.
getParameterNames() Returns an enumeration of parameter names.
getParameterMap() Returns a map of parameter names to their values.

8. Reading HTTP Request Headers

HTTP request headers carry metadata about the request. They can contain information such as accepted content types, client preferences, authentication details, and caching instructions.

String userAgent = request.getHeader("User-Agent");
String acceptedTypes = request.getHeader("Accept");
String authorization = request.getHeader("Authorization");

String method = request.getMethod();
String requestURI = request.getRequestURI();

System.out.println("User-Agent: " + userAgent);
System.out.println("Accept: " + acceptedTypes);
System.out.println("Method: " + method);
System.out.println("URI: " + requestURI);

Useful Request Methods

  • getHeader(String name) retrieves a header value.
  • getHeaders(String name) retrieves all values for a header.
  • getHeaderNames() lists available header names.
  • getMethod() returns the HTTP method, such as GET or POST.
  • getRequestURI() returns the request URI path.
  • getContextPath() returns the application's context path.
  • getQueryString() returns the raw query string, if present.

Do not trust request headers as proof of identity or authorization. For example, the User-Agent header can be changed by the client.

9. Reading and Setting Cookies

Cookies allow a web application to store small pieces of data in the browser and receive them on subsequent requests. They are often used for session identifiers and certain user preferences.

Reading Cookies from a Request

Cookie[] cookies = request.getCookies();

if (cookies != null) {
    for (Cookie cookie : cookies) {
        System.out.println(
            cookie.getName() + " = " + cookie.getValue()
        );
    }
}

Adding a Cookie to a Response

Cookie preference = new Cookie("theme", "dark");
preference.setMaxAge(60 * 60 * 24);
preference.setHttpOnly(true);
preference.setSecure(true);
preference.setPath("/");

response.addCookie(preference);

Security note: The Secure flag should be enabled when the application is served over HTTPS. HttpOnly prevents client-side JavaScript from reading the cookie. For sensitive cookies, configure an appropriate SameSite policy through supported container settings or response-cookie APIs.

10. Working with HttpSession

HTTP is stateless by default, which means that separate requests are not automatically treated as belonging to the same user. The servlet API provides HttpSession to maintain server-side state across requests.

HttpSession session = request.getSession();
session.setAttribute("username", "Rahul");

String username =
    (String) session.getAttribute("username");

response.setContentType("text/plain");
response.getWriter().println(
    "Logged-in user: " + username
);

Important Session Methods

  • getSession() retrieves the current session or creates one if needed.
  • getSession(false) retrieves the current session without creating a new one.
  • setAttribute() stores an object in the session.
  • getAttribute() retrieves an object from the session.
  • removeAttribute() removes a stored attribute.
  • invalidate() invalidates the session.

After authentication, applications should protect session identifiers, use HTTPS, and consider session ID rotation to reduce session-fixation risks.

11. Setting Response Content Type and Encoding

The response content type informs the browser or API client how to interpret the response body. Character encoding specifies how text characters are represented.

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");

response.getWriter().write(
    "{\"message\":\"Request processed successfully\"}"
);

Common content types include:

  • text/html for HTML pages.
  • text/plain for plain text.
  • application/json for JSON responses.
  • application/xml for XML responses.
  • application/pdf for PDF documents.

For production applications, use a JSON library to serialize Java objects instead of manually constructing JSON strings. This avoids formatting and escaping errors.

12. Writing Response Data

The servlet API provides two main ways to write response content: a character writer and a binary output stream.

Using PrintWriter

response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");

PrintWriter writer = response.getWriter();
writer.println("Welcome to the application.");
writer.println("Your request was processed.");

Using ServletOutputStream

response.setContentType("application/octet-stream");

ServletOutputStream output =
    response.getOutputStream();

byte[] data = "Sample file content"
    .getBytes(java.nio.charset.StandardCharsets.UTF_8);

output.write(data);

Use getWriter() for character-based content and getOutputStream() for binary data such as files and images. Do not use both for the same response body.

13. Setting HTTP Status Codes

An HTTP status code communicates the result of the request. Appropriate status codes help browsers, API clients, and monitoring systems understand whether an operation succeeded or failed.

Status Code Meaning Typical Use
200 OK Successful request. Returning a page or data.
201 Created A resource was created. Successful resource creation in an API.
204 No Content Successful request with no response body. Successful deletion or update when no content is required.
400 Bad Request The request is invalid. Missing or invalid required parameters.
401 Unauthorized Valid authentication is required. Missing or invalid authentication credentials.
403 Forbidden The operation is not permitted. An authenticated user lacks permission.
404 Not Found The resource was not found. Unknown URL or missing record.
500 Internal Server Error An unexpected server error occurred. Unanticipated server-side failure.
response.setStatus(
    HttpServletResponse.SC_CREATED
);

Choose the status code based on the actual result. Avoid returning a successful status for a failed operation.

14. Redirecting the Client

The sendRedirect() method instructs the client to make a new request to another URL. It is commonly used after a successful form submission or when directing a user to a login page.

@WebServlet("/submit")
public class SubmitServlet extends HttpServlet {

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {

        // Validate and process submitted data here.

        response.sendRedirect(
            request.getContextPath() + "/success"
        );
    }
}

A redirect normally uses an HTTP 302 response by default, depending on the Servlet API and container behavior. For permanent or method-preserving redirects, select the appropriate status and API supported by your environment.

Do not redirect blindly to a URL supplied by the user. Validate redirect destinations to prevent open-redirect vulnerabilities.

15. Forwarding a Request to Another Resource

Request forwarding allows a servlet to transfer processing to another server-side resource using a RequestDispatcher. Unlike a redirect, forwarding does not require the browser to make a new request.

request.setAttribute(
    "message",
    "Welcome to the dashboard"
);

RequestDispatcher dispatcher =
    request.getRequestDispatcher("/dashboard.jsp");

dispatcher.forward(request, response);

Forward vs. Redirect

Feature Forward Redirect
Execution Server-side transfer. Client makes another request.
URL in browser Normally remains unchanged. Changes to the redirect destination.
Request attributes Available to the forwarded resource. Not automatically preserved in the new request.
Request count Uses the existing request. Usually creates a new request.
Typical use Forwarding to a JSP for rendering. Redirecting after a successful form submission.

A forward must occur before the response is committed. Once response output has been committed, forwarding may fail with an IllegalStateException.

16. Handling Form Data Safely

Servlets frequently receive data from login forms, registration pages, contact forms, and search interfaces. All client-submitted values must be treated as untrusted.

Recommended Validation Steps

  1. Check whether required parameters exist.
  2. Trim values where appropriate.
  3. Validate lengths, formats, ranges, and allowed values.
  4. Convert numeric values safely and handle parsing errors.
  5. Use prepared statements when accessing a database.
  6. Apply authorization checks before performing protected operations.
  7. Encode output appropriately when displaying user-supplied content in HTML.
  8. Return meaningful status codes without exposing internal system details.
String ageValue = request.getParameter("age");
int age;

try {
    age = Integer.parseInt(ageValue);
} catch (NumberFormatException ex) {
    response.sendError(
        HttpServletResponse.SC_BAD_REQUEST,
        "Invalid age value"
    );
    return;
}

if (age < 0 || age > 120) {
    response.sendError(
        HttpServletResponse.SC_BAD_REQUEST,
        "Age is outside the permitted range"
    );
    return;
}

// Continue processing the validated age.

In real applications, also handle missing values before parsing and avoid returning detailed exception messages to clients.

17. Using Request Attributes

Request attributes allow servlets, filters, and other server-side components to share objects during the processing of a single request. They are particularly useful when forwarding data to a JSP.

request.setAttribute(
    "courseName",
    "Advanced Java"
);

request.setAttribute(
    "duration",
    "8 Weeks"
);

request.getRequestDispatcher("/course.jsp")
       .forward(request, response);

In a JSP, the attributes can be accessed using expression language, such as ${courseName} and ${duration}, when the JSP environment is configured appropriately.

Request attributes are different from request parameters: parameters originate from the incoming request, while attributes are objects stored by server-side code.

18. Common Errors and Troubleshooting

Problem Possible Cause Solution
Parameter returns null Incorrect field name or missing form value. Check the input's name attribute and request method.
Incorrect characters appear Character encoding mismatch. Configure request encoding before reading parameters and set response encoding.
Response is empty No output was written or an incorrect route was used. Verify servlet mapping and response-writing logic.
Cannot forward request Response already committed. Forward before writing or flushing response output.
IllegalStateException Attempt to modify a committed response or mix incompatible output methods. Set headers before writing and choose one output mechanism.
404 Not Found Incorrect URL mapping or application context path. Check @WebServlet, deployment settings, and URL.
405 Method Not Allowed The servlet does not handle the HTTP method. Implement the appropriate doGet(), doPost(), or other supported handler.
Session data disappears Session expired, invalidated, or not associated with the request. Check session lifecycle and cookie configuration.

19. Security Best Practices

  • Validate inputs: Never assume parameters or headers are safe.
  • Use HTTPS: Protect credentials, session identifiers, and sensitive information in transit.
  • Prevent SQL injection: Use parameterized queries and prepared statements.
  • Prevent cross-site scripting: Encode untrusted data for the correct output context.
  • Protect sessions: Use secure cookie settings and invalidate sessions during logout.
  • Apply authorization: Verify that the current user can perform each requested operation.
  • Avoid sensitive logging: Do not log passwords, session IDs, access tokens, or unnecessary personal data.
  • Handle errors carefully: Return safe error messages and log useful diagnostic information on the server.
  • Prevent CSRF: Use appropriate CSRF protections for state-changing requests, especially cookie-authenticated applications.
  • Control caching: Set suitable cache headers for sensitive responses.

20. Practical Example: Processing a Contact Form

This example shows a simple servlet that accepts contact information through a POST request, validates the fields, and returns a response. It demonstrates the request-response workflow without connecting to a database.

HTML Form

<form action="contact" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <button type="submit">Send</button>
</form>

Contact Servlet

@WebServlet("/contact")
public class ContactServlet extends HttpServlet {

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {

        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String email = request.getParameter("email");

        if (name == null || name.isBlank()
                || email == null || email.isBlank()) {

            response.sendError(
                HttpServletResponse.SC_BAD_REQUEST,
                "Name and email are required."
            );
            return;
        }

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(
            HttpServletResponse.SC_OK
        );

        response.getWriter().println(
            "Thank you, " + name
                + ". Your contact request was received."
        );
    }
}

Production note: This demonstration validates only that the fields are present. A production application should validate email format, encode user-supplied data for its output context, and implement appropriate storage, privacy, and abuse-prevention measures.

21. Best Practices for Writing Servlets

  • Keep servlet classes focused on HTTP request handling.
  • Move business logic into service classes rather than placing everything in a servlet.
  • Use DAO or repository classes for database operations.
  • Avoid storing request-specific information in servlet instance fields because servlet instances can process multiple requests concurrently.
  • Use correct HTTP methods for the intended operation.
  • Set content types, character encodings, and status codes appropriately.
  • Prefer request forwarding for server-side rendering and redirects where a new client request is required.
  • Use a logging framework instead of relying on System.out.println() in production.
  • Test missing parameters, invalid input, unexpected HTTP methods, and failure scenarios.

22. Practice Exercises

  1. Create a servlet that reads a user's name from a GET request and displays a welcome message.
  2. Build a registration form that accepts name, email, and phone number using POST.
  3. Read the request method, request URI, and selected headers and display them safely.
  4. Create a servlet that returns a JSON response with an appropriate content type.
  5. Implement a login demonstration using session attributes and a logout endpoint that invalidates the session.
  6. Build a servlet that validates numeric input and returns HTTP 400 for invalid values.
  7. Compare forwarding and redirecting by implementing both in separate servlet endpoints.
  8. Write a servlet that creates a preference cookie and reads it during a later request.

23. Interview Questions and Answers

Q1. What is HttpServletRequest?

Answer: It is an interface that gives a servlet access to information about an incoming HTTP request, including parameters, headers, cookies, request attributes, and session access.

Q2. What is HttpServletResponse?

Answer: It is an interface used to construct an HTTP response, including its body, status code, headers, cookies, and redirects.

Q3. What is the difference between getParameter() and getAttribute()?

Answer: getParameter() reads a client-submitted request parameter as a string. getAttribute() retrieves an object stored on the request by server-side code.

Q4. What is the difference between sendRedirect() and forward()?

Answer: A redirect tells the client to make a new request, while a forward transfers processing to another server-side resource using the existing request.

Q5. What is the purpose of setContentType()?

Answer: It specifies the media type of the response, such as text/html, text/plain, or application/json.

Q6. Can a servlet read multiple values for one parameter?

Answer: Yes. getParameterValues() returns an array of strings, which is useful for multi-select controls and checkbox groups.

Q7. What is HttpSession?

Answer: It is an API for maintaining server-side user state across multiple HTTP requests.

Q8. Why should request parameters be validated?

Answer: Client input is untrusted. Validation helps prevent invalid data, application errors, and security vulnerabilities.

Q9. What happens if response content has already been committed?

Answer: Some response properties can no longer be changed, and attempting operations such as forwarding or certain redirects may fail.

Q10. What is the difference between jakarta.servlet and javax.servlet?

Answer: They represent different package namespaces used by different generations of the Servlet API. Modern Jakarta-based containers use jakarta.servlet, while older Java EE containers commonly use javax.servlet. The application dependencies and container versions must be compatible.

24. Quick Revision

  • HttpServletRequest reads incoming request information.
  • HttpServletResponse creates outgoing HTTP responses.
  • getParameter() reads a single request parameter.
  • getParameterValues() reads multiple values for the same parameter.
  • getHeader() reads a request header.
  • getCookies() retrieves cookies sent by the client.
  • getSession() retrieves or creates an HTTP session.
  • setContentType() specifies the response media type.
  • setStatus() sets the response status code.
  • sendError() sends an HTTP error response.
  • sendRedirect() directs the client to another URL.
  • RequestDispatcher.forward() transfers processing to another server-side resource.
  • Validate client input and use secure coding practices in every servlet.

25. Conclusion

HttpServletRequest and HttpServletResponse form the foundation of HTTP communication in Java Servlet applications. The request interface enables developers to retrieve submitted data and understand the incoming request, while the response interface allows them to return content, set status codes, manage headers, and control client navigation.

Understanding these interfaces is essential for developing form-processing applications, session-based web systems, server-rendered pages, and REST-style endpoints. Practice using their methods, validate all incoming data, and follow security best practices when building production applications.

Explore the Advanced Java Training Course at JustAcademy to learn more about Java web development and enterprise application technologies.

To learn more about the training program, register for a course demo or visit the JustAcademy website.

Previous Next
whatsapp